<template>
  <div class="upload-box">
    <el-upload
      v-model:file-list="fileList"
      :accept="fileType.join(',')"
      :action="uploadUrl"
      :before-upload="beforeUpload"
      :class="['upload', drag ? 'no-border' : '']"
      :disabled="disabled"
      :drag="drag"
      :http-request="httpRequest"
      :limit="limit"
      :multiple="true"
      :on-error="uploadError"
      :on-exceed="handleExceed"
      :on-success="uploadSuccess"
      :on-remove="handleRemove"
      list-type="picture-card"
    >
      <div class="upload-empty">
        <slot name="empty">
          <Icon icon="ep:plus" />
        </slot>
      </div>
      <template #file="{ file }">
        <img :src="file.url" class="upload-image" />
        <div class="upload-handle" @click.stop>
          <div class="handle-icon" @click="imagePreview(file.url!)">
            <Icon icon="ep:zoom-in" />
            <span>查看</span>
          </div>
          <div v-if="!disabled" class="handle-icon" @click="handleRemoveFile(file)">
            <Icon icon="ep:delete" />
            <span>删除</span>
          </div>
        </div>
      </template>
    </el-upload>
    <div class="el-upload__tip">
      <slot name="tip"></slot>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { UploadFile, UploadProps, UploadUserFile } from 'element-plus'
import { ElNotification } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { propTypes } from '@/utils/propTypes'
import { useUpload } from '@/components/UploadFile/src/useUploadV2'

defineOptions({ name: 'UploadImgsV2' })

const message = useMessage()

// 查看图片
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    zIndex: 9999999,
    urlList: [imgUrl]
  })
}

type FileTypes =
  | 'image/apng'
  | 'image/bmp'
  | 'image/gif'
  | 'image/jpeg'
  | 'image/pjpeg'
  | 'image/png'
  | 'image/svg+xml'
  | 'image/tiff'
  | 'image/webp'
  | 'image/x-icon'

const props = defineProps({
  // 接收父组件传递的完整文件列表（包含id和url等信息）
  modelValue: propTypes.array.def([]),
  drag: propTypes.bool.def(true),
  disabled: propTypes.bool.def(false),
  limit: propTypes.number.def(5),
  fileSize: propTypes.number.def(5),
  fileType: propTypes.array.def(['image/jpeg', 'image/png', 'image/gif']),
  height: propTypes.string.def('150px'),
  width: propTypes.string.def('150px'),
  borderradius: propTypes.string.def('8px'),
  directory: propTypes.string.def(undefined)
})

// 定义事件：只通知父组件执行操作，不传递列表
const emit = defineEmits<{
  (e: 'file-uploaded', file: { url: string; name: string; id?: number }): void
  (e: 'file-removed', file: { url: string; name: string; id?: number }): void
}>()

const { uploadUrl, httpRequest } = useUpload(props.directory)

// 文件列表完全由父组件控制
const fileList = ref<UploadUserFile[]>([])

// 监听父组件传入的列表变化，完全同步父组件数据
watch(
  () => props.modelValue,
  (newVal) => {
    fileList.value = (newVal || []).map((item) => ({
      ...item,
      uid: item.uid || item.id || Date.now(), // 用id作为唯一标识（el-upload必须）
      status: 'success' // 标记为“已上传”状态，el-upload会显示为已完成的图片
    })) as UploadUserFile[]
  },
  { immediate: true, deep: true }
)

/**
 * 文件上传之前判断
 */
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize
  const imgType = props.fileType

  if (!imgType.includes(rawFile.type as FileTypes)) {
    ElNotification({
      title: '温馨提示',
      message: '上传图片不符合所需的格式！',
      type: 'warning'
    })
    return false
  }

  if (!imgSize) {
    ElNotification({
      title: '温馨提示',
      message: `上传图片大小不能超过 ${props.fileSize}M！`,
      type: 'warning'
    })
    return false
  }

  return true
}

// 图片上传成功：只通知父组件，不本地更新
const uploadSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: UploadFile) => {
  message.success('上传成功')
  // 通知父组件上传成功，由父组件处理后续并重新获取列表
  emit('file-uploaded', {
    data: response.data
  })
}

// 处理文件删除：只通知父组件，不本地删除
const handleRemoveFile = (file: UploadUserFile & { id?: number }) => {
  // 通知父组件删除，由父组件处理并重新获取列表
  emit('file-removed', {
    url: file.url!,
    name: file.name,
    id: file.id
  })

  // 不本地删除，等待父组件重新获取数据
}

// 处理组件自带的删除事件
const handleRemove: UploadProps['onRemove'] = (file) => {
  handleRemoveFile(file as UploadUserFile & { id?: number })
}

// 图片上传错误提示
const uploadError = () => {
  ElNotification({
    title: '温馨提示',
    message: '图片上传失败，请重新上传！',
    type: 'error'
  })
}

// 文件数超出提示
const handleExceed = () => {
  ElNotification({
    title: '温馨提示',
    message: `当前最多只能上传 ${props.limit} 张图片，请移除后上传！`,
    type: 'warning'
  })
}
</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
.is-error {
  .upload {
    :deep(.el-upload--picture-card),
    :deep(.el-upload-dragger) {
      border: 1px dashed var(--el-color-danger) !important;

      &:hover {
        border-color: var(--el-color-primary) !important;
      }
    }
  }
}

:deep(.disabled) {
  .el-upload--picture-card,
  .el-upload-dragger {
    cursor: not-allowed;
    background: var(--el-disabled-bg-color) !important;
    border: 1px dashed var(--el-border-color-darker);

    &:hover {
      border-color: var(--el-border-color-darker) !important;
    }
  }
}

.upload-box {
  .no-border {
    :deep(.el-upload--picture-card) {
      border: none !important;
    }
  }

  :deep(.upload) {
    .el-upload-dragger {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      padding: 0;
      overflow: hidden;
      border: 1px dashed var(--el-border-color-darker);
      border-radius: v-bind(borderradius);

      &:hover {
        border: 1px dashed var(--el-color-primary);
      }
    }

    .el-upload-dragger.is-dragover {
      background-color: var(--el-color-primary-light-9);
      border: 2px dashed var(--el-color-primary) !important;
    }

    .el-upload-list__item,
    .el-upload--picture-card {
      width: v-bind(width);
      height: v-bind(height);
      background-color: transparent;
      border-radius: v-bind(borderradius);
    }

    .upload-image {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }

    .upload-handle {
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      width: 100%;
      height: 100%;
      cursor: pointer;
      background: rgb(0 0 0 / 60%);
      opacity: 0;
      box-sizing: border-box;
      transition: var(--el-transition-duration-fast);
      align-items: center;
      justify-content: center;

      .handle-icon {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 0 6%;
        color: aliceblue;

        .el-icon {
          margin-bottom: 15%;
          font-size: 140%;
        }

        span {
          font-size: 100%;
        }
      }
    }

    .el-upload-list__item {
      &:hover {
        .upload-handle {
          opacity: 1;
        }
      }
    }

    .upload-empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 12px;
      line-height: 30px;
      color: var(--el-color-info);

      .el-icon {
        font-size: 28px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .el-upload__tip {
    line-height: 15px;
    text-align: center;
  }
}
</style>
